package com.ligoudan.config;


import com.ligoudan.converter.Converter;
import com.ligoudan.model.GenImageModel;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Logger;

public class ConfigHelper {

    private static final Logger LOGGER = Logger.getLogger(ConfigHelper.class.getName());

    public synchronized Properties loadConfig() {

        File configFile = new File("config.xml");
        if (!configFile.exists()) {
            try {
                if (!configFile.createNewFile()) {
                    LOGGER.warning("Create config.xml failed.");
                }
                return new Properties();
            } catch (IOException e) {
                e.printStackTrace();
                LOGGER.warning("Create config.xml thrown exception, using default config.");
                return new Properties();
            }
        }

        Properties properties = new Properties();
        try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(configFile))) {
            properties.loadFromXML(in);
            return properties;
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.warning("Load config.xml thrown exception, using default config.");
            return new Properties();
        }
    }

    public synchronized void storageConfig(GenImageModel model) {
        Properties properties = Converter.model2Config(model);
        storageConfig(properties);
    }

    private void storageConfig(Properties config) {
        BufferedOutputStream out = null;
        try {
            out = new BufferedOutputStream(new FileOutputStream("config.xml"));
            config.storeToXML(out, "genImageConfig", "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException ignore) {
                }
            }
        }
    }

}
